package com.ygqh.baby.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: sunshuo
 * @date: 2018/11/27 14:58
 */
public class WebUtil {

	private final static Logger logger = LoggerFactory.getLogger(WebUtil.class);

	/**
	 * 获取客户端ip地址
	 *
	 * @param request
	 * @return
	 */
	public static String getCliectIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || "".equals(ip.trim()) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || "".equals(ip.trim()) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || "".equals(ip.trim()) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		// 多个路由时，取第一个非unknown的ip
		final String[] arr = ip.split(",");
		for (final String str : arr) {
			if (!"unknown".equalsIgnoreCase(str)) {
				ip = str;
				break;
			}
		}
		return ip;
	}

	/**
	 * 判断是否为ajax请求
	 *
	 * @param request
	 * @return
	 */
	public static String getRequestType(HttpServletRequest request) {
		return request.getHeader("X-Requested-With");
	}

	/**
	 * 生成端连接信息
	 *
	 * @param url
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String generateShortUrl(String url) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("url_long", url.trim());
		params.put("source", "3271760578");
		try {
			String jsonStr = HttpUtil.post("http://api.t.sina.com.cn/short_url/shorten.json", params);
			JSONObject object = JSONObject.parseObject(JSONArray.parseArray(jsonStr).getString(0));
			return object.get("url_short").toString();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return url;
	}
}
